package com.open.launcher.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.open.launcher.R;
import com.open.launcher.base.MyApplication;
import com.open.launcher.base.SysApplication;
import com.open.launcher.bean.LiveListBean;
import com.open.launcher.bean.allchannels.Channles;
import com.open.launcher.bean.allchannels.Program;
import com.open.launcher.bean.details.PlayDetailsBean;
import com.open.launcher.callback.IRequestCallback;
import com.open.launcher.presenter.PlayerPresneter;
import com.open.launcher.service.AHservice;
import com.open.launcher.utils.APPLog;
import com.open.launcher.utils.Consts;
import com.open.launcher.utils.Paths;
import com.open.launcher.utils.SystemTimeDate;
import com.open.launcher.view.ScrollTextView;
//import com.open.launcher.view.utils.CacheDataPresenter;
import com.open.library.utils.PreferencesUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

import static android.content.ContentValues.TAG;

public class PlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnInfoListener {
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    private MediaPlayer currentPlayer;
    private SurfaceHolder currentHolder;
    private String playUrl = "";
    //private String playUrl = "rtsp://10.1.64.132:554/vod/00000050280000029893.mpg?userid=B91000379&stbip=10.129.234.26&clienttype=1&mediaid=&ifcharge=1&time=20171018164228+08&life=172800&usersessionid=2463700&vcdnid=001&boid=001&srcboid=001&columnid=&backupagent=10.1.64.132:554&ctype=50&playtype=0&Drm=0&EpgId=epg_nj_003&programid=00000050280000029893&contname=&fathercont=&bp=0&authid=0&tscnt=0&tstm=0&tsflow=0&ifpricereqsnd=1&nodelevel=3&usercharge=C5D06BCB9AA9FBBBE0BE71516394EFD4";
    private int TIME_OVER = 1;
    private int BROW_TEIM = 3;
    private int UPDATA_NUMBER = 8;
    private int TO_PLAYER = 9;
    private int HIDE_WINDOW = 10;
    private int LIVE_CHANNEL = 11;
    private int PROGRAM_CHANNEL = 12;
    private FrameLayout singleView;
    private ImageView pasusImage;
    private SeekBar progressBar;
    private TextView currentText;
    private TextView alText;
    private PlayDetailsBean detailsBean;
    private PlayerPresneter mPlayerPresneter;
    private int count;
    private int allCount;
    private String currentTime;
    private String allTime;
    private TextView program_name;
    private TextView actor_text;
    private TextView info_text;
    private ScrollTextView test_happy_view;
    private int SET_ADD_DURATION = 0x04;
    private int SET_REDUCE_DURATION = 0x05;
    private int SET_SEEK_TO = 0x06;
    private RelativeLayout bar_layout;
    private int type;
    private static final int VOD_TYPE = 1001; ///电影
    private static final int TELE_TYPE = 1000; //电视剧
    private static final int LIVE_TYPE = 1002;//直播
    private static final int TVOD_TYPE = 1003;//回看
    private static final int SKIP_TYPE = 1004;//默认播放频道
    private static final int COLLECTION = 1006;//收藏
    private static final int CHANNEL = 1007;
    private int CANCLE_TYPE = 1005;//下一集
    private int NEXT_TYPE = 1004;//下一集
    private RelativeLayout play_type;
    private RelativeLayout play_actor_type;
    private TextView live_number;
    private Channles.LivesBean mProgram;
    private RelativeLayout activity_player;
    private String sourcesList;
    private int number = -1;
    private int indexId;
    private int index;
    private int Current_Type;//当前播放状态
    private List<LiveListBean> liveList;
    private String numberText = "";
    //直播
    private TextView live_name;
    private TextView live_current_text;
    private TextView time_current_text;
    private TextView live_play_later;
    private TextView time_play_later;
    private int currentPosition;
    private SharedPreferences sharePreferences;
    private int programId;
    private RelativeLayout pause_layout;
//    private List<Program.Epg> epgLists;
    private int positions;
    private int liveId;
    private String liveUrl;
    private Intent intent;
    private FrameLayout channelListLayout;
    private PlayWindowFragment playWindowFragment;
    private int CHANGE_CHANNEL = 1008;
    private static final  int DESTORY_MEDIA = 1009;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        Log.i(TAG, "onCreate: ");
        initView();
        SysApplication.getInstance().addActivity(this);
        intent = getIntent();
        if (intent!=null) {
            type = intent.getIntExtra("type", 0);
            if (type==0){
                type=LIVE_TYPE;
                singleView.setVisibility(View.GONE);
            }
        }
        choosePlayType();
        initData();
    }
    private void choosePlayType(){
        switch (type) {
            case VOD_TYPE:
                //电影
                Current_Type = VOD_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                detailsBean = (PlayDetailsBean) intent.getSerializableExtra("data");
                int position1 = intent.getIntExtra("position", 0);
                if (detailsBean.getEpisodes()!=null){
                    if (detailsBean.getEpisodes().size()>0){
                playUrl = detailsBean.getEpisodes().get(position1).getUrl();}
                }
                break;
            case TELE_TYPE:
                //电影
                Current_Type = TELE_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                detailsBean = (PlayDetailsBean) intent.getSerializableExtra("data");
                int position2 = intent.getIntExtra("position", 0);
                currentPosition = position2;
                if (position2 >= detailsBean.getEpisodes().size()) {
                    return;
                }
                playUrl = detailsBean.getEpisodes().get(position2).getUrl();
                break;
            case LIVE_TYPE:
                //直播
                Current_Type = LIVE_TYPE;
                play_type.setVisibility(View.GONE);
//                play_actor_type.setVisibility(View.VISIBLE);
//                mProgram = (Program) intent.getSerializableExtra("data");

                if (MyApplication.liveListBeen != null) {
                    liveList = MyApplication.liveListBeen;
                    for (int i = 0; i < liveList.size(); i++) {
                        LiveListBean liveListBean = liveList.get(0);
                        if (!TextUtils.isEmpty(liveListBean.getSources().get(0))) {
                            OkHttpUtils.post().url("http://"+PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_KEY)+ Paths.LIVE_STATISTIC)
                                    .addParams("id",liveListBean.getId()+"")
                                    .build()
                                    .execute(new StringCallback() {
                                        @Override
                                        public void onError(Call call, Exception e, int id) {
                                            Log.i(TAG, "onError: ");
                                        }

                                        @Override
                                        public void onResponse(String response, int id) {
                                            Log.i(TAG, "onResponse: "+response);
                                        }
                                    });
                            indexId = liveListBean.getId();
                            index = i;
                            programId = index;
                            writeChannelId(index);
                            number = liveListBean.getNumber();
                            sourcesList = liveListBean.getSources().get(0);
                            playUrl = sourcesList;
                            live_number.setText(liveListBean.getName());
                            live_number.setVisibility(View.VISIBLE);
                            mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                        }
                    }
                }
                break;
            case TVOD_TYPE:
                Current_Type = VOD_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                playUrl = intent.getStringExtra("playUrl");
                //Toast.makeText(this, "playUrl==>:" + playUrl, Toast.LENGTH_LONG).show();
                break;
            case SKIP_TYPE:
                Current_Type = LIVE_TYPE;
                type = LIVE_TYPE;
                play_type.setVisibility(View.GONE);
                play_actor_type.setVisibility(View.VISIBLE);
                indexId = intent.getIntExtra("index", 0);
                if (MyApplication.liveListBeen != null) {
                    liveList = MyApplication.liveListBeen;
                    for (int i = 0; i < liveList.size(); i++) {
                        LiveListBean liveListBean = liveList.get(i);
                        if (indexId == liveListBean.getId()) {
                            index = i;
                            programId = indexId;
                            number = liveListBean.getNumber();
                            sourcesList = liveListBean.getSources().get(0);
                            playUrl = sourcesList;
                            live_number.setText(liveListBean.getNumber() + "");
                            live_number.setVisibility(View.VISIBLE);
                            mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                        }
                    }
                }
                break;
        }
    }
    private void initView() {
        surfaceView = (SurfaceView) this.findViewById(R.id.player_view);
        singleView = (FrameLayout) this.findViewById(R.id.single_bar);
        pasusImage = (ImageView) this.findViewById(R.id.pause_image);
        progressBar = (SeekBar) this.findViewById(R.id.seek_bar);
        alText = (TextView) this.findViewById(R.id.all_tiem);
        currentText = (TextView) this.findViewById(R.id.current_tiem);
        bar_layout = (RelativeLayout) this.findViewById(R.id.bar_layout);
        sharePreferences = getSharedPreferences("channel", 0);
        program_name = (TextView) findViewById(R.id.program_name);
        actor_text = (TextView) findViewById(R.id.actor_text);
        info_text = (TextView) findViewById(R.id.info_text);
        pause_layout = (RelativeLayout) findViewById(R.id.pause_layout);
        test_happy_view = (ScrollTextView) findViewById(R.id.s_tv);
        test_happy_view.startScroll();

        play_type = (RelativeLayout) findViewById(R.id.play_type);
        play_actor_type = (RelativeLayout) findViewById(R.id.play_actor_type);
        live_number = (TextView) findViewById(R.id.live_number);
        live_number.setTypeface(MyApplication.face);
        activity_player = (RelativeLayout) findViewById(R.id.activity_player);

        //直播
        live_name = (TextView) findViewById(R.id.live_name);
        live_current_text = (TextView) findViewById(R.id.live_current_text);
        time_current_text = (TextView) findViewById(R.id.time_current_text);
        live_play_later = (TextView) findViewById(R.id.live_play_later);
        time_play_later = (TextView) findViewById(R.id.time_play_later);

        channelListLayout = (FrameLayout) this.findViewById(R.id.channel_list);
    }

    private void initData() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("PlayerActivity");
        registerReceiver(receiver, filter);
        live_name.setTypeface(MyApplication.face);
        live_current_text.setTypeface(MyApplication.face);
        time_current_text.setTypeface(MyApplication.face);
        live_play_later.setTypeface(MyApplication.face);
        time_play_later.setTypeface(MyApplication.face);
        alText.setTypeface(MyApplication.face);
        currentText.setTypeface(MyApplication.face);
        program_name.setTypeface(MyApplication.face);
        actor_text.setTypeface(MyApplication.face);
        info_text.setTypeface(MyApplication.face);
        mPlayerPresneter = new PlayerPresneter(this);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

        if (type == 1002) {
            bar_layout.setVisibility(View.INVISIBLE);
            pasusImage.setVisibility(View.INVISIBLE);
            currentText.setVisibility(View.INVISIBLE);
            alText.setVisibility(View.INVISIBLE);
        }
        switch (type) {
            case VOD_TYPE:
            case TELE_TYPE:
                //电视剧/电影
                if (detailsBean != null) {
                    program_name.setText(detailsBean.getName());
                    //导演：王晶，孙总   演员：徐总|孙总|百望山
                    actor_text.setText("导演：" + detailsBean.getDirector() + "      演员：" + detailsBean.getStaring());
                    info_text.setText(detailsBean.getInfo());
//                    CacheDataPresenter.getPresenter(this).cacheRecord(detailsBean, "record_data", 20);
                }
                bar_layout.requestFocus();
                bar_layout.setOnKeyListener(new OnKeyListen());
                break;
            case LIVE_TYPE:
                //直播
                mPlayerPresneter.setCallback(callback);
                mPlayerPresneter.setDisplayed(true);
                mPlayerPresneter.loadVodItem(indexId);
                break;
        }

        pasusImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentPlayer.isPlaying()) {
                    currentPlayer.pause();
                } else {
                    currentPlayer.start();
                }
            }
        });
        if (Contast.CHANNEL_MARQUEE != null) {
            test_happy_view.setVisibility(View.VISIBLE);
            test_happy_view.setText(Contast.CHANNEL_MARQUEE);
        }
    }

    private void setLinsenter() {
        //mPlayWindowPresennter.setIClickPosition(new PlayWindowFragment.IClickPosition() {
        //    @Override
        //    public void callbackPosition(Program program) {
        //        if (program != null && currentHolder != null) {
        //            playUrl = program.getSources().get(0);
        //            Log.d("tag", "----playUrl----" + playUrl);
        //            crearPlayer(currentHolder, playUrl);
        //            mProgram = program;
        //            writeChannelId(program.getId());
        //
        //            mPlayerPresneter.setCallback(callback);
        //            mPlayerPresneter.setDisplayed(true);
        //            mPlayerPresneter.loadVodItem(program.getId());
        //        }
        //    }
        //
        //    @Override
        //    public void lookBackCallback(String url, int programId, List<Program.Epg> epgList, int position) {
        //        Log.d("tag", "----url----" + url);
        //        String startTime = epgList.get(position).getStarttime();
        //        String endTime = epgList.get(position).getEndtime();
        //        String reviewUrl = url + "?begin=" + startTime + "&end=" + endTime;
        //        Current_Type = TVOD_TYPE;
        //        type = TVOD_TYPE;
        //        bar_layout.setVisibility(View.VISIBLE);
        //        pasusImage.setVisibility(View.VISIBLE);
        //        currentText.setVisibility(View.VISIBLE);
        //        alText.setVisibility(View.VISIBLE);
        //        bar_layout.requestFocus();
        //        crearPlayer(currentHolder, reviewUrl);
        //        writeChannelId(programId);
        //        liveUrl = url;
        //        epgLists = epgList;
        //        liveId = programId;
        //        positions = position;
        //        APPLog.printInfo("programid==>:"+ programId);
        //        mPlayerPresneter.setCallback(callback);
        //        mPlayerPresneter.setDisplayed(true);
        //        mPlayerPresneter.loadVodItem(programId);
        //    }
        //});
    }

    public void updataTime() {
        mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        this.currentHolder = holder;
        mHandler.sendEmptyMessage(CHANNEL);
        //crearPlayer(holder, playUrl);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onBufferingUpdate(MediaPlayer player, int i) {

    }

    @Override
    public void onCompletion(MediaPlayer player) {
//        if (type == TELE_TYPE) {
//            if (epgLists != null) {
//                positions = positions + 1;
//                if (positions < epgLists.size()) {
//                    String startTime = epgLists.get(positions).getStarttime();
//                    String endTime = epgLists.get(positions).getEndtime();
//                    //http://192.168.0.39:8081/0001/index.m3u8?begin=0&end=1499003542
//                    String reviewUrl = liveUrl + "?begin=" + startTime + "&end=" + endTime;
//                    crearPlayer(currentHolder, reviewUrl);
//                }
//            }
//        } else {
//            finish();
//        }
    }

    @Override
    public boolean onError(MediaPlayer player, int i, int i1) {
        return false;
    }

    @Override
    public boolean onInfo(MediaPlayer player, int i, int i1) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer player) {
        if(mHandler.hasMessages(DESTORY_MEDIA)){
            mHandler.removeMessages(DESTORY_MEDIA);
        }
        if (player != null) {
            try {
                currentPlayer = player;
                currentPlayer.start();
                if (Current_Type != 1002) {
                    allCount = currentPlayer.getDuration();
                    progressBar.setMax(allCount);
                    allTime = SystemTimeDate.formatTime(allCount);
                    currentTime = SystemTimeDate.formatTime(0);
                    currentText.setText(currentTime);
                    alText.setText(allTime);
                    mHandler.sendEmptyMessage(BROW_TEIM);
                    APPLog.printInfo("allCount:" + allCount);
                }
            }catch (Exception e){
                APPLog.printInfo("e:"+e);
            }
        }
    }

    public void crearPlayer(SurfaceHolder holder, String url) {

        if (currentPlayer != null) {
            try {
                currentPlayer.stop();
                currentPlayer.release();
                currentPlayer = null;
            } catch (Exception e) {
                Log.d("creatPlayer", "creatPlayer==>:" + e);
            }
        }
        currentPlayer = new MediaPlayer();
        currentPlayer.setOnPreparedListener(this);
        currentPlayer.setDisplay(holder);//把视频画面输出到surfaceview上
        try {
            currentPlayer.setDataSource(url);
            mHandler.sendEmptyMessageDelayed(DESTORY_MEDIA,3000);
            currentPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(Current_Type!=TVOD_TYPE) {
//            singleView.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(1, 6000);
        }
    }

    @Override
    protected void onStop() {
        if (currentPlayer != null) {
            currentPlayer.stop();
            currentPlayer.release();
            currentPlayer = null;
        }
        super.onStop();
    }

    //快进循环发送消息
    public void setAddDuration() {
        mHandler.sendEmptyMessageDelayed(SET_ADD_DURATION, 1000);
    }

    //快退循环发送
    public void setReduceDuration() {
        mHandler.sendEmptyMessageDelayed(SET_REDUCE_DURATION, 1000);
    }

//    @Override
//    public void destroyFragment(PlayWindowFragment playWindowFragment) {
//        this.playWindowFragment = playWindowFragment;
//    }

    public class OnKeyListen implements View.OnKeyListener {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.d("tag", "--------OnKeyEvent--------" + keyCode);
            if ((keyCode == 22 || keyCode == 90) && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (singleView.getVisibility() == View.INVISIBLE) {
                    singleView.setVisibility(View.VISIBLE);
                }
                if (mHandler.hasMessages(BROW_TEIM)) {
                    mHandler.removeMessages(BROW_TEIM);
                }
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_SEEK_TO)) {
                    mHandler.removeMessages(SET_SEEK_TO);
                }
                APPLog.printInfo("count==>:" + count);
                setAddDuration();
                return true;
            } else if ((keyCode == 22 || keyCode == 90) && event.getAction() == KeyEvent.ACTION_UP) {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_ADD_DURATION)) {
                    mHandler.removeMessages(SET_ADD_DURATION);
                }
                mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                //mHandler.sendEmptyMessageDelayed(SET_SEEK_TO, 1000);
                mHandler.sendEmptyMessage(SET_SEEK_TO);
                APPLog.printInfo("快进====");
                return true;
//			setCurrentPosition(mediaPlayer,tv_player_control_time);
            } else if ((keyCode == 21 || keyCode == 89) && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mHandler.hasMessages(BROW_TEIM)) {
                    mHandler.removeMessages(BROW_TEIM);
                }
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_SEEK_TO)) {
                    mHandler.removeMessages(SET_SEEK_TO);
                }
                setReduceDuration();
                return true;
            } else if ((keyCode == 21 || keyCode == 89) && event.getAction() == KeyEvent.ACTION_UP) {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_REDUCE_DURATION)) {
                    mHandler.removeMessages(SET_REDUCE_DURATION);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
                mHandler.sendEmptyMessage(SET_SEEK_TO);
                return true;
            } else if ((keyCode == 23 || keyCode == 86) && event.getAction() == KeyEvent.ACTION_DOWN) {
                //Toast.makeText(PlayerActivity.this, "暂停", Toast.LENGTH_SHORT).show();
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                if (currentPlayer != null) {
                    if (currentPlayer.isPlaying()) {
                        currentPlayer.pause();
                        pause_layout.setVisibility(View.VISIBLE);
                    } else {
                        currentPlayer.start();
                        pause_layout.setVisibility(View.GONE);
                    }
                }
                return true;
            }
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Toast.makeText(this, "requestCode:" + requestCode + "resultCode:" + resultCode, Toast.LENGTH_LONG).show();
        if (resultCode == CANCLE_TYPE && requestCode == VOD_TYPE) {
            if (currentPlayer != null) {
                currentPlayer.stop();
                currentPlayer.release();
                currentPlayer = null;
            }
            finish();
        } else if (resultCode == CANCLE_TYPE && requestCode == TELE_TYPE) {
            if (currentPlayer != null) {
                currentPlayer.stop();
                currentPlayer.release();
                currentPlayer = null;
            }
            finish();
        } else if (resultCode == NEXT_TYPE && requestCode == TELE_TYPE) {
            //Toast.makeText(this, "播放下一集", Toast.LENGTH_SHORT).show();
            currentPosition++;
            if (detailsBean.getEpisodes().size() > currentPosition) {
                playUrl = detailsBean.getEpisodes().get(currentPosition).getUrl();
                crearPlayer(currentHolder, playUrl);
                pause_layout.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, "已经是最后一集了", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == CANCLE_TYPE && requestCode == LIVE_TYPE) {
            if (currentPlayer != null) {
                if (playWindowFragment!=null){
//                    getFragmentManager().beginTransaction().remove(playWindowFragment).commit();
//                    playWindowFragment.mHandler.removeMessages(0x2);
//                    playWindowFragment.getActivity().onBackPressed();
                }
                currentPlayer.stop();
                currentPlayer.release();
                currentPlayer = null;
            }
            finish();
        } else if (resultCode == LIVE_TYPE && requestCode == LIVE_TYPE) {

        } else if (resultCode == CANCLE_TYPE && requestCode == TVOD_TYPE) {
            if (currentPlayer != null) {
                currentPlayer.stop();
                currentPlayer.release();
                currentPlayer = null;
            }
            finish();
        } else if (requestCode == TVOD_TYPE && requestCode == TVOD_TYPE) {

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        outState.putBoolean("fragment",true);
//        super.onSaveInstanceState(outState);
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("tag", "--------KeyEvent--------" + keyCode);
        if ((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(Current_Type == TVOD_TYPE){
                return true;
            }
            if (Current_Type==LIVE_TYPE){
                return true;
            }
            if (singleView.getVisibility() == View.INVISIBLE) {
                singleView.setVisibility(View.VISIBLE);
                bar_layout.requestFocus();
                mHandler.sendEmptyMessage(BROW_TEIM);
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                if(playWindowFragment == null || !playWindowFragment.onBackPressed()){
//                    if(getFragmentManager().getBackStackEntryCount() == 0){
//                        super.onBackPressed();
////                        if (playWindowFragment!=null) {
////                            getFragmentManager().beginTransaction().remove(playWindowFragment).commit();
////                        }
//                    }else{
//                        getFragmentManager().popBackStack();
//                    }
//                }


                Intent intent = new Intent(this, ExitActivity.class);
                switch (type) {
                    case VOD_TYPE:
                        intent.putExtra("playType", VOD_TYPE);
                        startActivityForResult(intent, VOD_TYPE);
                        break;
                    case TELE_TYPE:
                        intent.putExtra("playType", TELE_TYPE);
                        startActivityForResult(intent, TELE_TYPE);
                        break;
                    case LIVE_TYPE:
                        intent.putExtra("playType", LIVE_TYPE);
                        startActivityForResult(intent, TELE_TYPE);
                        break;
                    case TVOD_TYPE:
                        intent.putExtra("playType", TVOD_TYPE);
                        startActivityForResult(intent, TVOD_TYPE);
                        break;
                }
            }
            return true;
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9 && event.getAction() == KeyEvent.ACTION_DOWN) {
            setNumber(keyCode);
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) && event.getAction() == KeyEvent.ACTION_DOWN) {
             if(mHandler.hasMessages(0x11)){
                 return true;
             }
            if (liveList==null){
                Toast.makeText(getApplicationContext(),"暂无节目",Toast.LENGTH_SHORT).show();
                return true;
            }
             mHandler.sendEmptyMessageDelayed(0x11,1000);
            if(Current_Type == LIVE_TYPE) {
                if (playWindowFragment == null) {//||getFragmentManager().popBackStack()
                    playWindowFragment = new PlayWindowFragment();
                    playWindowFragment.setContext(this);
                    playWindowFragment.setMainHandler(mHandler);
                    playWindowFragment.setFragmentManager(getFragmentManager());
                }
                getFragmentManager().beginTransaction().add(R.id.channel_list, playWindowFragment).commit();
                //getFragmentManager().beginTransaction().show(playWindowFragment).commit();
                APPLog.printInfo("开始显示频道列表");
                //Toast.makeText(this, "按了确定", Toast.LENGTH_SHORT).show();
            }else {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                if (currentPlayer != null) {
                    if (currentPlayer.isPlaying()) {
                        currentPlayer.pause();
                        pause_layout.setVisibility(View.VISIBLE);
                    } else {
                        currentPlayer.start();
                        pause_layout.setVisibility(View.GONE);
                    }
                }
            }
            return true;
        } else if((keyCode == KeyEvent.KEYCODE_DPAD_DOWN|| keyCode == KeyEvent.KEYCODE_CHANNEL_DOWN)&& event.getAction() == KeyEvent.ACTION_DOWN){
            if (Current_Type == LIVE_TYPE) {
                if (liveList==null){
                    Toast.makeText(getApplicationContext(),"暂无节目",Toast.LENGTH_SHORT).show();
                    return true;
                }
                if(index>=0){
                    index --;
                    if(index<0){
                        index = liveList.size()-1;
                        //Toast.makeText(this, "已经是第一个频道哦!", Toast.LENGTH_SHORT).show();
                    }
                    if(liveList!=null){
                        if(mHandler.hasMessages(UPDATA_NUMBER)){
                            mHandler.removeMessages(UPDATA_NUMBER);
                        }
                        if(mHandler.hasMessages(CHANGE_CHANNEL)){
                            mHandler.removeMessages(CHANGE_CHANNEL);
                        }
                        LiveListBean listBean = liveList.get(index);
                        Log.d("tag", "----DOWN--->" + listBean.getName());
                        sourcesList = listBean.getSources().get(0);
                        live_number.setText(listBean.getName());
                        live_number.setVisibility(View.VISIBLE);
                        Message message = mHandler.obtainMessage();
                        message.what=CHANGE_CHANNEL;
                        message.obj=listBean;
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
//                        mHandler.sendEmptyMessageDelayed(CHANGE_CHANNEL,1000);
                        mHandler.sendMessageDelayed(message,1000);
                    }
                }
            }
            return true;
        }else if((keyCode == KeyEvent.KEYCODE_DPAD_UP|| keyCode == KeyEvent.KEYCODE_CHANNEL_UP)&& event.getAction() == KeyEvent.ACTION_DOWN){
            if (Current_Type == LIVE_TYPE) {
                if (liveList==null){
                    Toast.makeText(getApplicationContext(),"暂无节目",Toast.LENGTH_SHORT).show();
                    return true;
                }
                if(index<liveList.size()){
                    index ++;
                    if(index>=liveList.size()){
                        index = 0;
                        //Toast.makeText(this, "已经是第一个频道哦!", Toast.LENGTH_SHORT).show();
                    }
                    if(liveList!=null){
                        if(mHandler.hasMessages(UPDATA_NUMBER)){
                            mHandler.removeMessages(UPDATA_NUMBER);
                        }
                        if(mHandler.hasMessages(CHANGE_CHANNEL)){
                            mHandler.removeMessages(CHANGE_CHANNEL);
                        }
                        LiveListBean listBean = liveList.get(index);
                        Log.d("tag", "----DOWN--->" + listBean.getName());
                        sourcesList = listBean.getSources().get(0);
                        live_number.setText(listBean.getName() + "");
                        live_number.setVisibility(View.VISIBLE);
                        Message message = mHandler.obtainMessage();
                        message.what=CHANGE_CHANNEL;
                        message.obj=listBean;
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
//                        mHandler.sendEmptyMessageDelayed(CHANGE_CHANNEL,1000);
                        mHandler.sendMessageDelayed(message,1000);
                    }
                }
            }
            return true;
        }
        return false;
    }

    private PlayerPresneter.Callback callback = new PlayerPresneter.Callback() {
        @Override
        public void onError(int code, String msg) {

        }

        @Override
        public void onPlayerUrlCompleted(PlayerPresneter presenter, int count) {
            if (presenter != null) {
                presenter.onBindMovieView(itemViewHolder, count);
                play_actor_type.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessageDelayed(TIME_OVER,6*1000);
            }
        }
    };
    private PlayerPresneter.ItemViewHolder itemViewHolder = new PlayerPresneter.ItemViewHolder() {
        @Override
        public void setChannelName(String name) {
            live_name.setText(name);
        }

        @Override
        public void setCurrentPlay(String text) {
            live_current_text.setText(text);
        }

        @Override
        public void setCurrentPlayTime(String text) {
            time_current_text.setText(text);
        }

        @Override
        public void setLaterPlay(String text) {
            live_play_later.setText(text);
        }

        @Override
        public void setLaterPlaytime(String text) {
            time_play_later.setText(text);
        }
    };

    private void setNumber(int number) {
        number -= 7;
        if (numberText != null && numberText.length() < 2) {
            numberText = numberText + number;
            live_number.setText(numberText);
            live_number.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(TO_PLAYER, 3000);
        } else if (numberText != null && numberText.length() == 2) {
            numberText = numberText + number;
            live_number.setText(numberText);
            live_number.setVisibility(View.VISIBLE);
            Message message = new Message();
            message.what = TO_PLAYER;
            mHandler.sendMessageDelayed(message, 1000);
        }
    }

    //public class SetOnClick implements View.OnClickListener {
    //    @Override
    //    public void onClick(View view) {
    //        if (handler.hasMessages(TIME_OVER)) {
    //            handler.removeMessages(TIME_OVER);
    //        }
    //        handler.sendEmptyMessageDelayed(1, 6000);
    //        if (currentPlayer != null && currentPlayer.isPlaying()) {
    //            currentPlayer.pause();
    //        } else if (currentPlayer != null) {
    //            currentPlayer.start();
    //        }
    //    }
    //}

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_OVER) {
                singleView.setVisibility(View.INVISIBLE);
            } else if (msg.what == BROW_TEIM) {
                try {
                    count = currentPlayer.getCurrentPosition();
                    String curTime = SystemTimeDate.formatTime(count);
                    int allTime = currentPlayer.getDuration();
                    currentText.setText(curTime);
                    progressBar.setProgress(count);
                    if(count>=allTime - 3000){
                        finish();
                        return;
                    }
                    //int allCount = currentPlayer.getDuration();
                    //Toast.makeText(PlayerActivity.this, "总长度为："+ count, Toast.LENGTH_SHORT).show();
                    //APPLog.printInfo(allCount + "count====>:" + count);
                    updataTime();
                } catch (Exception e) {
                    APPLog.printInfo("获取长度异常：" + e);
                }
            } else if (msg.what == SET_ADD_DURATION) {
                if (progressBar != null) {
                    if (count != allCount - 10000) {
                        count += 10 * 1000;
                    }
                    if (count >= allCount) {
                        count = allCount - 10000;
                    }
                    if (count == allCount - 10000) {
                        return;
                    }
                    //Toast.makeText(PlayerActivity.this, allCount + "count==>:" + count, Toast.LENGTH_SHORT).show();
                    APPLog.printInfo("addcount:" + count);
                    progressBar.setProgress(count);
                    //setAddDuration();
                    String currentTime = SystemTimeDate.formatTime(count);
                    currentText.setText(currentTime);
                }
            } else if (msg.what == SET_REDUCE_DURATION) {
                if (progressBar != null) {
                    count -= 10 * 1000;
                    if (count <= 0) {
                        count = 0;
                    }
                    if (count == 0) {
                        return;
                    }
                    progressBar.setProgress(count);
                    //setAddDuration();
                    String currentTime = SystemTimeDate.formatTime(count);
                    currentText.setText(currentTime);
                }
            } else if (msg.what == SET_SEEK_TO) {
                if(currentPlayer!=null) {
                    currentPlayer.seekTo(count);
                }
                //mHandler.removeMessages(BROW_TEIM);
            } else if (msg.what == UPDATA_NUMBER) {
                live_number.setVisibility(View.GONE);
            } else if (msg.what == TO_PLAYER) {
                boolean isexist = false;
                if (liveList==null){
                    Toast.makeText(PlayerActivity.this, "暂无节目", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < liveList.size(); i++) {
                    LiveListBean liveListBean = liveList.get(i);
                    if (liveListBean != null && numberText.equals(liveListBean.getNumber() + "")) {
                        OkHttpUtils.post().url("http://"+PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_KEY)+Paths.LIVE_STATISTIC)
                                .addParams("id",liveListBean.getId()+"")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Log.i(TAG, "onError: ");
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        Log.i(TAG, "onResponse: "+response);
                                    }
                                });
                        sourcesList = liveListBean.getSources().get(0);
                        index = i;
                        playUrl = sourcesList;
                        crearPlayer(currentHolder, playUrl);
                        isexist = true;
                        writeChannelId(liveListBean.getId());
                        mPlayerPresneter.loadVodItem(liveListBean.getId());
                    }
                }
                live_number.setVisibility(View.GONE);
                numberText = "";
                if (!isexist) {
                    Toast.makeText(PlayerActivity.this, "暂无节目", Toast.LENGTH_SHORT).show();
                }
            } else if (msg.what == HIDE_WINDOW) {
                //if (mPlayWindowPresennter != null) {
                //    mPlayWindowPresennter.hideView();
                //}
            }else if(msg.what == CHANNEL){
                try{
                    if(!"".endsWith(playUrl)) {
                        crearPlayer(currentHolder, playUrl);
                    }
                }catch (Exception e){
                    APPLog.printInfo("播放失败");
                }
            }else if(msg.what == LIVE_CHANNEL){
                Channles.LivesBean program = (Channles.LivesBean) msg.obj;
                if (program != null && currentHolder != null) {
                    playUrl = program.getSources().get(0);
                    Log.d("tag", "----playUrl----" + playUrl);
                    crearPlayer(currentHolder, playUrl);
                    mProgram = program;
                    writeChannelId(program.getId());

                    mPlayerPresneter.setCallback(callback);
                    mPlayerPresneter.setDisplayed(true);
                    mPlayerPresneter.loadVodItem(program.getId());

                    indexId = mProgram.getId();
                    if (liveList==null){
                        Toast.makeText(PlayerActivity.this, "暂无节目", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (MyApplication.liveListBeen != null) {
                        liveList = MyApplication.liveListBeen;
                        for (int i = 0; i < liveList.size(); i++) {
                            LiveListBean liveListBean = liveList.get(i);
                            if (indexId == liveListBean.getId()) {
                                index = i;
                                programId = indexId;
                                number = liveListBean.getNumber();
                                live_number.setText(liveListBean.getName());
                                live_number.setVisibility(View.VISIBLE);
                                mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                            }
                        }
                    }
                }
            }else if(msg.what == PROGRAM_CHANNEL){
                Bundle bundle = (Bundle) msg.obj;
                Current_Type = bundle.getInt("type");
                //play_type.setVisibility(View.VISIBLE);
                //play_actor_type.setVisibility(View.GONE);
                playUrl = bundle.getString("reviewUrl");
                crearPlayer(currentHolder, playUrl);
            }else if(msg.what == CHANGE_CHANNEL) {
                LiveListBean obj = (LiveListBean) msg.obj;
                playUrl = obj.getSources().get(0);
                int id = obj.getId();
                if (liveList != null && index >= 0) {
                    LiveListBean listBean = liveList.get(index);
                    if (sourcesList != null & !TextUtils.isEmpty(sourcesList)) {
                        OkHttpUtils.post().url("http://"+PreferencesUtils.getString(getApplicationContext(), Consts.IP_ADDR_KEY)+Paths.LIVE_STATISTIC)
                                .addParams("id",id+"")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Log.i(TAG, "onError: ");
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        Log.i(TAG, "onResponse: "+response);
                                    }
                                });
                    }
                    if (playUrl != null) {
                        crearPlayer(currentHolder, playUrl);
//                        int id = listBean.getId();
                        writeChannelId(id);
                        //Toast.makeText(PlayerActivity.this, "-------index---------" + index + "-----id-----" + id + "----playUrl----" + playUrl, Toast.LENGTH_SHORT).show();
                        mPlayerPresneter.loadVodItem(id);
                    }
                }
            }else if(msg.what == DESTORY_MEDIA){
                if (currentPlayer != null) {
                    try {
                        currentPlayer.stop();
                        currentPlayer.release();
                        currentPlayer = null;
                    } catch (Exception e) {
                        Log.d("creatPlayer", "creatPlayer==>:" + e);
                    }
                    //Toast.makeText(PlayerActivity.this, "销毁播放器", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    public void writeChannelId(int id) {
        SharedPreferences.Editor editor = sharePreferences.edit();
        editor.putInt("id", id);
        editor.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(currentPlayer!=null){
            currentPlayer.pause();
            currentPlayer.reset();
            currentPlayer = null;
        }
        unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (type == LIVE_TYPE) {
                if (intent != null) {
                    int type = intent.getIntExtra("type", 0);
                    if (type == COLLECTION) {
//                        CacheDataPresenter.getPresenter(PlayerActivity.this).saveLiveProgram(mProgram);
                    }
                }
            }
        }
    };

    private void load() {
        AHservice service = new AHservice();
        service.loadVodItemData("http://"+ PreferencesUtils.getString(this, Consts.IP_ADDR_KEY) + Paths.PROGRAM_LIVE + "/" + programId, new IRequestCallback() {
            @Override
            public void onLoadComplete(String contentID, int pageNumber, int count, Object dto) {

                if (dto != null && dto instanceof Program) {
                    mProgram = (Channles.LivesBean) dto;
                }
            }

            @Override
            public void onLoading(String contentID) {

            }

            @Override
            public void onFailed(String code, String msg) {

            }
        });
    }
}
